<?php
ini_set('memory_limit','750M');
ini_set('set_time_limit',900);
set_include_path ( $_SERVER ['DOCUMENT_ROOT'] );
include_once 'admin/includes/functions/admin-functions.php';
global $DBobject, $SMARTY, $CONFIG;

$error = "Session has expired. Please refresh the page.";
$success = false;

$referer = parse_url($_SERVER['HTTP_REFERER']);
if( $referer['host'] == $GLOBALS['HTTP_HOST'] && checkToken('admin', $_POST["formToken"])){
	$template = '';
	$attachmentFile = '';
	$userId = 0;
	$error = 'Email cannot be sent.';
	
	$to = $_POST['email'];
	$bcc = '';
	$from = (string) $CONFIG->company->name;
	$fromEmail = 'noreply@'. str_replace('www.', '', $GLOBALS['HTTP_HOST']);
	$COMP = json_encode($CONFIG->company);
	$SMARTY->assign('COMPANY', json_decode($COMP,TRUE));
	$SMARTY->assign('DOMAIN', "http://" . $GLOBALS['HTTP_HOST']);
	
	if(!empty($_POST['status'])){
		$template = 'email-order-status.tpl';
		switch($_POST['status']){	//ADDITIONAL CUSTOM MESSAGE / TEMPLATE
			//CANCELLED
			case '6':
			case '10':
				$sql = "SELECT * FROM tbl_email_additional WHERE email_additional_id = :id "; //Status - Order cancelled
				if($res = $DBobject->wrappedSql ( $sql, array(':id' => 19)) ){ 
					$message = unclean($res[0]['email_additional_content']);
				}
				break;
			
			//APRROVED - BANK TRANSFER
			case '4':
			case '5':
				$sql = "SELECT * FROM tbl_email_additional WHERE email_additional_id = :id "; //Bank Transfer Approved
				if($res = $DBobject->wrappedSql ( $sql, array(':id' => 5)) ){ 
					$message = unclean($res[0]['email_additional_content']);
				}
				break;
				
			default:
				$message = '';
				
		}
		if(!empty($template)){
			$sql = "SELECT * FROM tbl_status WHERE status_id = :id ";
			$res = $DBobject->wrappedSql ( $sql, array(':id' => $_POST["status"]) );
			//$subject = 'Your order status has been changed to ' . strtolower($res[0]['status_category']) . '.';
			$subject ='澳睿跑 (Ready Steady Go Kids) | 订单 '. ucwords(strtolower($res[0]['status_category']));
			$SMARTY->assign('message',$message);
				
			$pay_obj = new Bank();
			$payment = $pay_obj->GetPaymentRecord($_POST["payment_id"]);
			$SMARTY->assign('payment',$payment);
			$debt = $pay_obj->GetDebtByPaymentId($_POST["payment_id"]);
			$SMARTY->assign('nextpayment', $debt['debt_nextpayment_date']);
			
			$member_obj = new Member();
			$userArr = $member_obj->RetrieveById($payment['payment_user_id']);
			$userId = $userArr['user_id'];
			$SMARTY->assign("user",array("gname"=>$userArr['user_gname']));
			$addressArr = $member_obj->GetAddress($payment['payment_shipping_address_id']);
			$SMARTY->assign('shipping',$addressArr);
			
			$enrol_obj = new Enrolment();
			$order = $enrol_obj->GetDataCart($payment['payment_cart_id']);
			$SMARTY->assign('order',$order);
				
			$orderItems = $enrol_obj->GetDataProductsOnCart($payment['payment_cart_id']);
			$SMARTY->assign('orderItems',$orderItems);
			
			$body = $SMARTY->fetch($template);
			
			
		}
	}elseif(!empty($_POST['action'])){
		switch($_POST['action']){
			case 'SendNewEmail':
			  $fromEmail = 'noreply@'. str_replace('www.', '', $GLOBALS['HTTP_HOST']);
			  if($_SESSION['user']['admin']["level"] > 1){
			    $fromEmail = $_SESSION['user']['admin']["email"];
			  }
			  $from = (string) $CONFIG->company->name;
				$error = 'Missing fields';
				if(!empty($_POST['email']) && !empty($_POST['subject']) && !empty($_POST['content'])){
					$to = $_POST['email'];
					$subject = unclean($_POST['subject']);
					$SMARTY->assign("content",unclean($_POST['content']));
			
					$body= $SMARTY->fetch('email-custom.tpl');
					$success = false;
					$error = 'Email cannot be sent.';
					$response = sendMail($to, $from, $fromEmail, $subject, $body, null, $_POST['user_id'], $_SESSION['user']['admin']["id"]);
					if($response){
						$error = null;
						$success = 'The email was successfully sent.';
						$member_obj = new Member();
						$SMARTY->assign('emails', $member_obj->GetMemberEmails($_POST['user_id']));
						$template = $SMARTY->fetch('table-emails.tpl');
					}
					echo json_encode(array(
							"error" => $error,
							"success" => $success,
							"template" => $template
					));
					die();
				}
			
			case 'ReSendEmail':
			  $fromEmail = 'noreply@'. str_replace('www.', '', $GLOBALS['HTTP_HOST']);
			  if($_SESSION['user']['admin']["level"] > 1){
			    $fromEmail = $_SESSION['user']['admin']["email"];
			  }
			  $from = (string) $CONFIG->company->name;
				$error = 'Missing fields';
				$sql = "SELECT * FROM tbl_email_queue WHERE email_id = :id ";
				if($res = $DBobject->wrappedSql( $sql, array(':id' => $_POST["email_id"]))){
					$sql = "SELECT user_email FROM tbl_user WHERE user_deleted IS NULL AND user_id = :id ";
					$res2 = $DBobject->wrappedSql( $sql, array(':id' => $res[0]['email_user_id']));
					$to = $res2[0]['user_email'];
					$subject = $res[0]['email_subject'];
					$body = $res[0]['email_content'];
					$userId = $res[0]['email_user_id'];
				}
				break;
				
				
			case 'SendEmailtoClasses':
			  $fromEmail = 'noreply@'. str_replace('www.', '', $GLOBALS['HTTP_HOST']);
			  if($_SESSION['user']['admin']["level"] > 1){
			    $fromEmail = $_SESSION['user']['admin']["email"];
			  }
			  $from = (string) $CONFIG->company->name;
				$recipients = array();
				$params = array();
				$sqlArr  = array();
				$weekno = 0;

				if(!empty($_POST['classes']) && !empty($_POST['term_object_id'])) {
					$params[":enrolment_term_object_id"] = $_POST['term_object_id'];
					$tsql = "SELECT IF(term_start_date < NOW(),CEIL(DATEDIFF(IF(term_end_date>NOW(),NOW(),term_start_date),SUBDATE(term_start_date, (DAYOFWEEK(term_start_date)-1)))/7),1) AS weekno FROM tbl_term WHERE term_deleted IS NULL AND term_published = 1 AND term_object_id = :enrolment_term_object_id";
					if($res = $DBobject->wrappedSql($tsql, $params)){
						$weekno = $res[0]['weekno'];
					}
					$params[":enrolment_week"] = $weekno;
					foreach ($_POST['classes'] as $class_object_id => $flag){
						$params[":enrolment_class_object_id{$class_object_id}"] = $class_object_id;
						$sqlArr[] = "enrolment_class_object_id = :enrolment_class_object_id{$class_object_id}"; 
					}
					
					
					
				}
				if(empty($sqlArr)){
					$error = "No classes were selected.";
					break;
				} 
				
				if(!empty($_POST['method']) && $_POST['method'] == 'sms'){
					$error = "There are no members (valid mobile numbers) associated to the selected class(es)";
					
					$sql = "SELECT DISTINCT(student_user_id) AS user_id FROM tbl_enrolment
											    LEFT JOIN tbl_student ON student_id = enrolment_student_id
											  WHERE student_deleted IS NULL
													AND enrolment_deleted IS NULL
													AND enrolment_published = '1'
											    AND enrolment_term_object_id = :enrolment_term_object_id
													AND enrolment_week >= :enrolment_week
													AND (". implode(' OR ', $sqlArr).") ";
					
					if($res = $DBobject->wrappedSql($sql, $params)){
						foreach ($res as $r){
							$sql = "SELECT address_telephone AS mobile FROM tbl_address WHERE address_deleted IS NULL AND address_user_id = :address_user_id ORDER BY address_modified DESC LIMIT 1" ;
							if($mob = $DBobject->wrappedSql($sql, array(':address_user_id' => $r['user_id']))){
								$temp = preg_replace('/\+|\s|\./', '', $mob[0]['mobile']);
								$phone = preg_replace('/^04/','614', $temp,1);
								if(preg_match("/^614/",$phone) && !in_array($mob[0]['mobile'],$sms_recipients))  $sms_recipients["{$r['user_id']}"] = $phone;
							}
					  }
					 
					  try{
					  	if(empty($sms_recipients)) break;
					  		
					  	$error = 'Error: Something went wrong. ';
					  	if($response = sendSMS($sms_recipients,$_POST['sms_content'], $_SESSION['user']['admin']["id"])){
					  		$success = $response['sent'] ." SMSs were successfully sent. ". (empty($response['error'])?"":"Failed: ".count($response['error']));
					  		echo json_encode(array(
					  				"response" => $response,
					  				"error" => null,
					  				"success" => $success
					  		));
					  		die();
					  	}
					  		
					  }catch(Exception $e){
					  	$to = "readysteadygokids@gmail.com-dev,online@them.com.au";
					  	sendMail($to, (string) $CONFIG->company->name, 'noreply@' . str_replace ( "www.", "", $GLOBALS['HTTP_HOST'] ), 'SMS Error', "Error: ".$e."</br> Recipients: ".print_r($sms_recipients,TRUE)." </br> Post: ".print_r($_POST,TRUE)." </br> Session: ".print_r($_SESSION,TRUE));
					  	$error .= $e .' - Please contact web administrator and DO NOT try again - ';
					  	break;
					  }
					}
				}else{
					$error = "There are no members associated to the selected class(es)";
					
					$sql = "SELECT user_id, user_email  
									  FROM tbl_enrolment
									    LEFT JOIN tbl_student ON student_id = enrolment_student_id
											LEFT JOIN tbl_user ON student_user_id = user_id
									  WHERE user_deleted IS NULL
											AND student_deleted IS NULL
											AND enrolment_deleted IS NULL
											AND enrolment_published = '1'
									    AND enrolment_term_object_id = :enrolment_term_object_id
											AND enrolment_week >= :enrolment_week
											AND (". implode(' OR ', $sqlArr).") 
				 				 GROUP BY user_email";
						
					if($res = $DBobject->wrappedSql($sql, $params)){
						$userKeys = array();
						foreach ($res as $r){
							$recipients[] = $r['user_email'];
							$userKeys[] = $r['user_id'];
						}
						
						if(empty($recipients)) break;
						
						$recipients[] = $_SESSION['user']['admin']["email"];
						$subject = $_POST["subject"];
						$SMARTY->assign("content",unclean($_POST['content']));
						$body = $SMARTY->fetch('email-custom.tpl');
						createBulkMail($recipients, $from, $fromEmail, $subject, $body, $_SESSION['user']['admin']["id"], $userKeys);
						$response = sendBulkMail();
						$error = '';
					}
				}
				$to = '';
				break;
				
				
			case 'NotifyFranchiseUser':
				$sql = "SELECT * FROM tbl_admin WHERE admin_id = :id ";
				$res = $DBobject->wrappedSql ( $sql, array(':id' => $_POST["admin_id"]) );
				$SMARTY->assign('admin',$res[0]);
				
				$subject = 'Welcome to Ready Steady Go Kids team';
				$file =  $_SERVER['DOCUMENT_ROOT'].'/uploads/pdfs/welcome-rsgk.pdf';
				$attachmentFile = file_exists($file) ? $file : '';
				
				$body = $SMARTY->fetch('email-welcome.tpl');
				break;
				
		}
		
		
		
	}
	
	if(!empty($to) && !empty($subject) && !empty($body)){
		if(empty($attachmentFile)){
			$response = sendMail($to, $from, $fromEmail, $subject, $body, $bcc, $userId, $_SESSION['user']['admin']["id"]);
		}else{
			$response = sendAttachMail($to, $from, $fromEmail, $subject, $body, $bcc, $attachmentFile, $userId, $_SESSION['user']['admin']["id"]);
		}
	}
	if($response){
		$error = null;
		$success = empty($success)?'The email was successfully sent.':$success;
	}
	echo json_encode(array(
			"response" => $response,
			"error" => $error,
			"success" => $success
	));
	die ();
	
	
}
echo json_encode(array(
		"response" => $response
));
die ();






